﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace RLGDashboard
{
    class MonitorAllSensors
    {
        private Thread monitorThread;

        public EgtSensor tempSensors;
        public PressureSensor psiSensors;
        public AFRSensor afrSensors;
        public RpmSensor rpmSensors;
        public VoltageSensor voltageSensors;
        private InQueue transmissionQueue;

        public MonitorAllSensors(ref InQueue transmissionQueue)
        {
            //Initialize all Sensors
            tempSensors = new EgtSensor();
            afrSensors = new AFRSensor();
            psiSensors = new PressureSensor();
            rpmSensors = new RpmSensor();
            voltageSensors = new VoltageSensor();

            //Save copy of the transmissionQueue
            this.transmissionQueue = transmissionQueue;

            monitor();
        }

        public void monitor()
        {
            monitorThread = new Thread(new ThreadStart(processTransmissions));
            monitorThread.Start();
        }

        private void processTransmissions()
        {
            EventWaitHandle waitHandle = new AutoResetEvent(false);

            while (monitorThread.IsAlive)
            {
                if (transmissionQueue.CurrentQueueCount != 0)
                {
                    process(transmissionQueue.readFromQueue());
                }
                else
                {
                    waitHandle.WaitOne(12);
                }
            }
        }

        private void process(BluetoothTransmission transmission)
        {
            switch (transmission.messageID)
            {
                case 0: tempSensors.updateValues(transmission); break;
                case 1: psiSensors.updateValues(transmission); break;
                case 2: rpmSensors.updatePulseRate(transmission); break;
                case 3: rpmSensors.updatePulseCount(transmission); break;
                case 4: voltageSensors.updateValues(transmission); break;
                case 5: afrSensors.updateValues(transmission); break;
            }
        }

        public void terminateListenThread()
        {
            if (monitorThread != null)
            {
                if (monitorThread.IsAlive)
                {
                    monitorThread.Abort();
                }
            }
        }
    }
}
